package com.lagou.edu.connector.protocol;

import com.lagou.edu.connector.Endpoint;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author liangzj
 * @date 2021/4/6 23:18
 */
public class Connector implements Endpoint {

    private String protocol;

    // 端口默认8080
    private int port = 8080;

    private ThreadPoolExecutor executor;

    private ServerSocket serverSocket;

    // 默认线程数
    private static final int THREAD_SIZE = 5;

    // 处理请求的线程池
    private ThreadPoolExecutor DEFAULT_ACCEPTOR_EXECUTOR = new ThreadPoolExecutor(
            THREAD_SIZE,
            THREAD_SIZE,
            100L,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(50),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());


    @Override
    public void create() throws IOException {
        serverSocket = new ServerSocket(port);
    }

    @Override
    public Socket getAcceptor() throws IOException {
        return serverSocket.accept();
    }

    @Override
    public ThreadPoolExecutor getExecutor() {
        return this.executor == null ? DEFAULT_ACCEPTOR_EXECUTOR : this.executor;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return port;
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }
}
